package com.example.shirodemo.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.Set;

/**
 * /**
 * ShiroTest   com.example.shirodemo.realm
 *
 * @author：黄玉刚 -成都电安惠科有限公司
 * @date： 2019/11/30 20:16
 * @Description ：
 */
public class MyRealm extends AuthorizingRealm {


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权认证----");
        //1. 从PricipalCollection 中获取登录用户的信息
        Object primaryPrincipal = principalCollection.getPrimaryPrincipal();
        //2. 利用登录的用户信息来获取当前用户的角色或权限（可能需要查询数据库）
        Set<String> roles = new HashSet<>();
        roles.add("user");
        if ("admin".equals(primaryPrincipal)) {
            roles.add("admin");
        }

        //3. 创建SimpleAuthorizationInfo ，并设置起roles属性
        SimpleAuthorizationInfo role = new SimpleAuthorizationInfo(roles);
        //4. 返回SimpleAuthorizationInfo对象
        return role;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        System.out.println("从数据库中获取UserName信息" + username + "  " + new String(usernamePasswordToken.getPassword()));
        if (!"user".equals(username)) {
            throw new UnknownAccountException("账户不存在！");
        }
        //1） pricipal :认证的实体信息，可以是user那么，也可以是实体对象
        //2） credential：密码
        //3） realname:当前realm对象的name，调用父类的getName()方法即可

        ByteSource credentialsSalt = ByteSource.Util.bytes("123");

        Object saltPassword = new SimpleHash("MD5", new String(usernamePasswordToken.getPassword()), credentialsSalt, 5);

        return new SimpleAuthenticationInfo(username, saltPassword.toString(), credentialsSalt, getName());

    }
}
